<script setup>
import { ref } from 'vue'
import ChannelSelest from './ChannelSelest.vue'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import {
  articlePostAddService,
  artGetDetailService,
  artEditService
} from '@/api/article.js'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { baseURL } from '@/utils/request'
import axios from 'axios'
const visibleDrawer = ref(false)

const defaultForm = {
  title: '',
  cate_id: '',
  cover_img: '',
  content: '',
  state: ''
}
const fromData = ref({
  ...defaultForm
})

const imgUrl = ref('')
const onUploadFile = (uploadFile) => {
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  fromData.value.cover_img = uploadFile.raw
}

const open = async (row) => {
  visibleDrawer.value = true
  if (row.id) {
    const res = await artGetDetailService(row.id)
    fromData.value = res.data.data
    imgUrl.value = baseURL + fromData.value.cover_img
    fromData.value.cover_img = await imageUrlToFile(
      imgUrl.value,
      fromData.value.cover_img
    )
    // 需要发请求
  } else {
    console.log('添加功能')
    fromData.value = { ...defaultForm }
  }
}
const editorRef = ref()
const emit = defineEmits(['success'])
const onPublish = async (state) => {
  fromData.value.state = state
  // 转换 formData 数据
  const fd = new FormData()
  for (let key in fromData.value) {
    fd.append(key, fromData.value[key])
  }

  if (fromData.value.id) {
    await artEditService(fd)
    ElMessage.success('编辑成功')
    visibleDrawer.value = false
    emit('success', 'edit')
  } else {
    // 添加请求
    await articlePostAddService(fd)
    ElMessage.success('添加成功')
    visibleDrawer.value = false
    emit('success', 'add')
  }
  imgUrl.value = ''
  editorRef.value.setHTML('')
}

// 将网络图片地址转换为File对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' })
    const imageData = response.data

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], {
      type: response.headers['content-type']
    })

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type })

    return file
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error)
    throw error
  }
}

defineExpose({
  open
})
</script>

<template>
  <el-drawer
    v-model="visibleDrawer"
    :title="fromData.id ? '编辑文章' : '添加文章'"
    direction="rtl"
    size="40%"
  >
    <!-- 发表文章表单 -->
    <el-form :model="fromData" label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="fromData.title"
          placeholder="请输入标题"
          style="width: 300px"
        ></el-input>
      </el-form-item>
      <el-form-item label="文章分类" prop="cate_id">
        <channel-selest
          v-model="fromData.cate_id"
          width="100%"
        ></channel-selest>
      </el-form-item>
      <el-form-item label="文章封面" prop="cover_img">
        <!-- 文件上传 -->
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="onUploadFile"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容" prop="content">
        <div class="editor">
          <quill-editor
            ref="editorRef"
            theme="snow"
            v-model:content="fromData.content"
            contentType="html"
          >
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onPublish('已发布')">发布</el-button>
        <el-button type="info" @click="onPublish('草稿')">草稿</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}

.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
</style>
